"use client"

import { useRef, useState } from "react"
import { View, Text, StyleSheet, TouchableOpacity, ScrollView, Platform, Pressable, Alert } from "react-native"
import { Volume2, BookmarkIcon, Check, XCircle } from "lucide-react-native"
import { theme } from "../../constants/theme"
import { Swipeable } from "react-native-gesture-handler"
import { CollectionModal } from "../learning/CollectionModal"
import { useRouter } from "expo-router"

// 单词条目的接口定义
interface VocabularyItem {
    id: string
    word: string
    phonetic: string
    meaning: string
    type: string
    syllables: string[]
    status: "needWrite" | "needRecognize" | "mastered" // 新学页面的状态
    favorite: boolean
    previousStatus?: "needWrite" | "needRecognize" | "new" | "learning" | null
}

// 特殊音节颜色映射
const SYLLABLE_COLORS = {
    mu: theme.colors.secondary.orange.default,
    tion: theme.colors.primary.default,
    vor: theme.colors.secondary.orange.default,
    tism: theme.colors.primary.default,
    bine: theme.colors.primary.default,
    ject: theme.colors.primary.default,
    ics: theme.colors.primary.default,
    pli: theme.colors.secondary.orange.default,
    fy: theme.colors.primary.default,
    ti: theme.colors.secondary.orange.default,
    ten: theme.colors.secondary.orange.default,
}

// 状态颜色映射
const STATUS_COLORS = {
    needWrite: "#FF9999", // 需会写 - 红色
    needRecognize: "#FF9500", // 需会认 - 橙色
    mastered: "#99CC99", // 标熟 - 绿色
}

interface NewLearningListProps {
    vocabularyData: VocabularyItem[]
    activeTab: string
    settings: {
        split: boolean
        fontSize: "small" | "medium" | "large"
    }
    selectedWordId: string | null
    onWordPress: (wordId: string) => void
    onUpdateStatus: (wordId: string, status: "needWrite" | "needRecognize" | "mastered") => void
    onToggleFavorite: (wordId: string) => void
    deleteMode?: boolean
    selectedWords?: string[]
    showFavoriteButton?: boolean
    onSwipeStateChange?: (isActive: boolean) => void
    isReviewMode?: boolean
}

export function NewLearningList({
    vocabularyData,
    activeTab,
    settings,
    selectedWordId,
    onWordPress,
    onUpdateStatus,
    onToggleFavorite,
    deleteMode = false,
    selectedWords = [],
    showFavoriteButton = true,
    onSwipeStateChange,
    isReviewMode = false,
}: NewLearningListProps) {
    const router = useRouter()
    const [revealedItems, setRevealedItems] = useState<Record<string, boolean>>({})
    const [isPlaying, setIsPlaying] = useState(false)
    const swipeableRefs = useRef<{ [key: string]: Swipeable | null }>({})

    const [collectionModalVisible, setCollectionModalVisible] = useState(false)
    const [selectedWordForCollection, setSelectedWordForCollection] = useState<string | null>(null)

    // 根据字号设置获取字体大小
    const getFontSize = () => {
        switch (settings.fontSize) {
            case "small":
                return theme.fontSize.sm
            case "large":
                return theme.fontSize.lg
            case "medium":
            default:
                return theme.fontSize.md
        }
    }

    // 渲染拆分单词
    const renderSplitWord = (word, syllables, fontSize) => {
        return (
            <View style={styles.splitWordContainer}>
                {syllables.map((syllable, index) => (
                    <Text
                        key={index}
                        style={[
                            styles.syllable,
                            {
                                fontSize,
                                color: SYLLABLE_COLORS[syllable] || theme.colors.neutral.black,
                                fontWeight: SYLLABLE_COLORS[syllable] ? theme.fontWeight.bold : theme.fontWeight.semiBold,
                            },
                        ]}
                    >
                        {syllable}
                    </Text>
                ))}
            </View>
        )
    }

    // 临时显示被遮挡的内容
    const toggleReveal = (itemId: string) => {
        setRevealedItems((prev) => ({
            ...prev,
            [itemId]: !prev[itemId],
        }))
    }

    // 模拟播放语音
    const playAudio = (word: string) => {
        if (isPlaying) return

        setIsPlaying(true)

        // 模拟播放音频
        Alert.alert("播放语音", `正在播放: "${word}"`, [{ text: "确定", onPress: () => setIsPlaying(false) }])

        // 2秒后自动关闭播放状态
        setTimeout(() => {
            setIsPlaying(false)
        }, 2000)
    }

    // 处理单词点击
    const handleWordPress = (wordId: string) => {
        // 关闭所有打开的滑动项
        if (!deleteMode) {
            Object.keys(swipeableRefs.current).forEach((key) => {
                if (key !== wordId && swipeableRefs.current[key]) {
                    swipeableRefs.current[key]?.close()
                }
            })
        }

        onWordPress(wordId)
    }

    // 处理详情按钮点击
    const handleDetailsPress = (word: string) => {
        console.log("详情按钮点击 - 单词:", word)
        // 导航到详情页面
        router.push(`/word-detail-screen?word=${word}`)
    }

    // 渲染滑动操作按钮 - 根据当前状态显示不同的按钮
    const renderRightActions = (wordId: string, currentStatus: string, isFavorite: boolean) => {
        // 如果当前是标熟状态，显示取消标熟按钮
        if (currentStatus === "mastered") {
            return (
                <View style={styles.swipeActionsContainer}>
                    {/* 取消标熟按钮 */}
                    <TouchableOpacity
                        style={styles.cancelMasteredButton}
                        onPress={() => {
                            // 找到单词的previousStatus，如果没有则默认为needRecognize
                            const word = vocabularyData.find((w) => w.id === wordId)
                            const prevStatus = word?.previousStatus || "needRecognize"
                            onUpdateStatus(wordId, prevStatus as any)
                            if (swipeableRefs.current[wordId]) {
                                swipeableRefs.current[wordId]?.close()
                            }
                        }}
                    >
                        <XCircle size={16} color="#FF3B30" />
                        <Text style={styles.cancelMasteredButtonText}>取消标熟</Text>
                    </TouchableOpacity>

                    {showFavoriteButton && (
                        <TouchableOpacity
                            style={styles.favoriteButton}
                            onPress={() => {
                                // 如果已收藏，直接取消收藏
                                if (isFavorite) {
                                    onToggleFavorite(wordId)
                                } else {
                                    // 如果未收藏，弹出收藏选择框
                                    setSelectedWordForCollection(wordId)
                                    setCollectionModalVisible(true)
                                }

                                if (swipeableRefs.current[wordId]) {
                                    swipeableRefs.current[wordId]?.close()
                                }
                            }}
                        >
                            <BookmarkIcon size={14} color="#8B5CF6" fill={isFavorite ? "#8B5CF6" : "none"} />
                        </TouchableOpacity>
                    )}
                </View>
            )
        }

        // 如果不是标熟状态，显示正常的状态按钮
        const statusConfig = [
            { id: "needWrite", label: "需会写", color: "#FFF1F1", borderColor: "#FF9999", activeColor: "#FF9999" },
            { id: "needRecognize", label: "需会认", color: "#FFF4E5", borderColor: "#FF9500", activeColor: "#FF9500" },
        ]

        return (
            <View style={styles.swipeActionsContainer}>
                {statusConfig.map((status) => (
                    <TouchableOpacity
                        key={status.id}
                        style={[
                            styles.statusButton,
                            { backgroundColor: status.color },
                            currentStatus === status.id && styles.activeStatusButton,
                        ]}
                        onPress={() => {
                            onUpdateStatus(wordId, status.id as any)
                            if (swipeableRefs.current[wordId]) {
                                swipeableRefs.current[wordId]?.close()
                            }
                        }}
                    >
                        <View
                            style={[
                                styles.statusIndicator,
                                { borderColor: status.borderColor },
                                currentStatus === status.id && {
                                    backgroundColor: status.activeColor,
                                    borderColor: status.activeColor,
                                },
                            ]}
                        />
                        <Text
                            style={[
                                styles.statusButtonText,
                                { color: status.borderColor },
                                currentStatus === status.id && { fontWeight: theme.fontWeight.semiBold },
                            ]}
                        >
                            {status.label}
                        </Text>
                    </TouchableOpacity>
                ))}

                {/* 标熟按钮 */}
                <TouchableOpacity
                    style={styles.masteredButton}
                    onPress={() => {
                        onUpdateStatus(wordId, "mastered")
                        if (swipeableRefs.current[wordId]) {
                            swipeableRefs.current[wordId]?.close()
                        }
                    }}
                >
                    <Check size={16} color={theme.colors.secondary.green.default} />
                    <Text style={styles.masteredButtonText}>标熟</Text>
                </TouchableOpacity>

                {showFavoriteButton && (
                    <TouchableOpacity
                        style={styles.favoriteButton}
                        onPress={() => {
                            // 如果已收藏，直接取消收藏
                            if (isFavorite) {
                                onToggleFavorite(wordId)
                            } else {
                                // 如果未收藏，弹出收藏选择框
                                setSelectedWordForCollection(wordId)
                                setCollectionModalVisible(true)
                            }

                            if (swipeableRefs.current[wordId]) {
                                swipeableRefs.current[wordId]?.close()
                            }
                        }}
                    >
                        <BookmarkIcon size={14} color="#8B5CF6" fill={isFavorite ? "#8B5CF6" : "none"} />
                    </TouchableOpacity>
                )}
            </View>
        )
    }

    // 添加滑动开始和结束的处理函数
    const handleSwipeStart = () => {
        if (onSwipeStateChange) {
            onSwipeStateChange(true)
        }
    }

    const handleSwipeEnd = () => {
        if (onSwipeStateChange) {
            onSwipeStateChange(false)
        }
    }

    return (
        <ScrollView style={styles.contentContainer} showsVerticalScrollIndicator={false}>
            {vocabularyData.map((item) => (
                <Swipeable
                    key={item.id}
                    ref={(ref) => (swipeableRefs.current[item.id] = ref)}
                    renderRightActions={() => renderRightActions(item.id, item.status, item.favorite)}
                    overshootRight={false}
                    friction={2}
                    rightThreshold={40}
                    containerStyle={styles.swipeableContainer}
                    childrenContainerStyle={styles.swipeableChildrenContainer}
                    enabled={!deleteMode} // 在删除模式下禁用滑动
                    onSwipeableWillOpen={handleSwipeStart}
                    onSwipeableOpen={handleSwipeStart}
                    onSwipeableClose={handleSwipeEnd}
                >
                    <TouchableOpacity
                        style={[
                            styles.wordCard,
                            selectedWordId === item.id && !deleteMode && styles.wordCardSelected,
                            deleteMode && selectedWords.includes(item.id) && styles.wordCardSelectedForDelete,
                            item.status === "mastered" && styles.wordCardMastered,
                        ]}
                        activeOpacity={0.9}
                        onPress={() => handleWordPress(item.id)}
                    >
                        {deleteMode && (
                            <View style={styles.checkboxContainer}>
                                <View style={[styles.checkbox, selectedWords.includes(item.id) && styles.checkboxSelected]}>
                                    {selectedWords.includes(item.id) && <Check size={16} color={theme.colors.neutral.white} />}
                                </View>
                            </View>
                        )}

                        <View style={[styles.wordCardContent, deleteMode && styles.wordCardContentWithCheckbox]}>
                            {/* 左侧：单词部分 */}
                            <View style={styles.wordSection}>
                                <View style={styles.wordContent}>
                                    <View style={styles.wordRow}>
                                        {settings.split ? (
                                            renderSplitWord(item.word, item.syllables, getFontSize())
                                        ) : (
                                            <Text style={[styles.word, { fontSize: getFontSize() }]}>{item.word}</Text>
                                        )}

                                        {/* 状态指示器 */}
                                        <View style={[styles.statusIndicator, { backgroundColor: STATUS_COLORS[item.status] }]} />

                                        {/* 收藏指示器 */}
                                        {item.favorite && (
                                            <BookmarkIcon size={14} color="#8B5CF6" fill="#8B5CF6" style={styles.favoriteIndicator} />
                                        )}
                                    </View>

                                    <View style={styles.phoneticRow}>
                                        <Text style={styles.phonetic}>{item.phonetic}</Text>

                                        {/* 音频按钮 - 更小更不显眼 */}
                                        <TouchableOpacity
                                            style={styles.audioButton}
                                            onPress={(e) => {
                                                e.stopPropagation()
                                                playAudio(item.word)
                                            }}
                                            disabled={isPlaying}
                                        >
                                            <Volume2 size={14} color={theme.colors.neutral.gray} />
                                        </TouchableOpacity>
                                    </View>
                                </View>

                                {/* 单词遮盖蒙版 */}
                                {activeTab === "words" && !deleteMode && (
                                    <Pressable style={styles.maskContainer} onPress={() => toggleReveal(`word-${item.id}`)}>
                                        {!revealedItems[`word-${item.id}`] && <View style={styles.mask} />}
                                    </Pressable>
                                )}
                            </View>

                            {/* 右侧：翻译部分 */}
                            <View style={styles.meaningSection}>
                                <View style={styles.meaningContainer}>
                                    <Text style={styles.type}>{item.type}</Text>
                                    <Text style={[styles.meaning, { fontSize: getFontSize() }]}>{item.meaning}</Text>
                                    {!deleteMode && (
                                        <TouchableOpacity
                                            style={styles.detailsButton}
                                            onPress={(e) => {
                                                e.stopPropagation()
                                                router.push(`/word-detail-screen?word=${item.word}`)
                                            }}
                                        >
                                            <Text style={styles.detailsText}>详情</Text>
                                        </TouchableOpacity>
                                    )}
                                </View>

                                {/* 翻译遮盖蒙版 */}
                                {activeTab === "translation" && !deleteMode && (
                                    <Pressable style={styles.maskContainer} onPress={() => toggleReveal(`meaning-${item.id}`)}>
                                        {!revealedItems[`meaning-${item.id}`] && <View style={styles.mask} />}
                                    </Pressable>
                                )}
                            </View>
                        </View>
                    </TouchableOpacity>
                </Swipeable>
            ))}
            <View style={{ height: 20 }} />
            <CollectionModal
                visible={collectionModalVisible}
                onClose={() => setCollectionModalVisible(false)}
                onConfirm={(unitId, bookId) => {
                    if (selectedWordForCollection) {
                        // 这里可以传递更多信息，如果需要的话
                        onToggleFavorite(selectedWordForCollection)
                        console.log(`收藏到: 课本ID=${bookId}, 单元ID=${unitId}`)
                    }
                    setCollectionModalVisible(false)
                    setSelectedWordForCollection(null)
                }}
            />
        </ScrollView>
    )
}

const styles = StyleSheet.create({
    contentContainer: {
        flex: 1,
        paddingHorizontal: theme.spacing.lg,
    },
    wordCard: {
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        marginBottom: theme.spacing.md,
        borderWidth: 2,
        borderColor: "transparent",
        flexDirection: "row",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.5,
                shadowRadius: 4,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    wordCardSelected: {
        borderColor: theme.colors.primary.default,
        backgroundColor: "#F0F5FF",
    },
    wordCardSelectedForDelete: {
        borderColor: theme.colors.secondary.green.default,
        backgroundColor: "#F1FFF1",
    },
    wordCardMastered: {
        backgroundColor: "#F1FFF1",
        borderColor: theme.colors.secondary.green.light,
    },
    wordCardContent: {
        flexDirection: "row",
        justifyContent: "space-between",
        flex: 1,
    },
    wordCardContentWithCheckbox: {
        marginLeft: theme.spacing.md,
    },
    checkboxContainer: {
        justifyContent: "center",
        marginRight: theme.spacing.sm,
    },
    checkbox: {
        width: 24,
        height: 24,
        borderRadius: 12,
        borderWidth: 2,
        borderColor: theme.colors.neutral.lightGray,
        alignItems: "center",
        justifyContent: "center",
    },
    checkboxSelected: {
        backgroundColor: theme.colors.secondary.green.default,
        borderColor: theme.colors.secondary.green.default,
    },
    wordSection: {
        flex: 1,
        marginRight: theme.spacing.lg,
        position: "relative",
    },
    wordContent: {
        justifyContent: "center",
    },
    wordRow: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: theme.spacing.xs,
        position: "relative",
    },
    phoneticRow: {
        flexDirection: "row",
        alignItems: "center",
    },
    audioButton: {
        marginLeft: theme.spacing.sm,
        padding: 2,
    },
    statusIndicator: {
        width: 8,
        height: 8,
        borderRadius: 4,
        marginLeft: theme.spacing.sm,
    },
    favoriteIndicator: {
        marginLeft: theme.spacing.xs,
    },
    meaningSection: {
        flex: 1.5,
        position: "relative",
    },
    word: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        flex: 1,
    },
    splitWordContainer: {
        flexDirection: "row",
        flexWrap: "wrap",
        flex: 1,
    },
    syllable: {
        marginRight: 2,
        fontWeight: theme.fontWeight.semiBold,
    },
    phonetic: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        fontFamily: "System",
    },
    meaningContainer: {
        flexDirection: "row",
        alignItems: "flex-start",
        flexWrap: "wrap",
    },
    type: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
        marginRight: theme.spacing.sm,
        marginTop: 2,
    },
    meaning: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        flex: 1,
    },
    detailsButton: {
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        paddingVertical: 2,
        paddingHorizontal: 6,
        borderRadius: theme.borderRadius.small,
        marginLeft: theme.spacing.sm,
    },
    detailsButtonText: {
        fontSize: 10,
        color: theme.colors.primary.default,
        marginLeft: 2,
    },
    maskContainer: {
        position: "absolute",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        zIndex: 10,
    },
    mask: {
        position: "absolute",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: "#E9E9E9",
        borderRadius: 4,
        zIndex: 20,
    },
    swipeableContainer: {
        backgroundColor: "transparent",
    },
    swipeableChildrenContainer: {
        backgroundColor: "transparent",
    },
    swipeActionsContainer: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "flex-end",
        paddingRight: theme.spacing.sm,
        height: "100%",
        gap: theme.spacing.xs,
    },
    statusButton: {
        height: 28,
        paddingHorizontal: theme.spacing.sm,
        borderRadius: theme.borderRadius.medium,
        flexDirection: "row",
        alignItems: "center",
        gap: theme.spacing.xs,
    },
    statusIndicator: {
        width: 12,
        height: 12,
        borderRadius: 6,
        borderWidth: 1,
        borderColor: theme.colors.neutral.darkGray,
    },
    activeStatusButton: {
        // 不需要额外样式
    },
    statusButtonText: {
        fontSize: 10,
        color: theme.colors.neutral.darkGray,
    },
    masteredButton: {
        height: 28,
        paddingHorizontal: theme.spacing.sm,
        borderRadius: theme.borderRadius.medium,
        flexDirection: "row",
        alignItems: "center",
        gap: theme.spacing.xs,
        backgroundColor: "#F1FFF1",
    },
    masteredButtonText: {
        fontSize: 10,
        color: theme.colors.secondary.green.default,
        fontWeight: theme.fontWeight.medium,
    },
    cancelMasteredButton: {
        height: 28,
        paddingHorizontal: theme.spacing.sm,
        borderRadius: theme.borderRadius.medium,
        flexDirection: "row",
        alignItems: "center",
        gap: theme.spacing.xs,
        backgroundColor: "#FFF1F1",
    },
    cancelMasteredButtonText: {
        fontSize: 10,
        color: "#FF3B30",
        fontWeight: theme.fontWeight.medium,
    },
    favoriteButton: {
        width: 28,
        height: 28,
        borderRadius: theme.borderRadius.medium,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "#F3E8FF",
    },
    detailsText: {
        fontSize: 10,
        color: theme.colors.primary.default,
        marginLeft: 2,
    },
})

